<template>
    <div class="app-container">

        <!-- 添加修改弹出层开始 -->
        <el-dialog
                :title="title"
                :visible.sync="formDialogVisible"
                width="500px"
                center
                append-to-body
        >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" placeholder="请输入角色名称" clearable size="small" />
                </el-form-item>
                <el-form-item label="权限编码" prop="roleCode">
                    <el-input v-model="form.roleCode" placeholder="请输入权限字符" clearable size="small" />
                </el-form-item>
                <el-form-item label="显示顺序" prop="roleSort">
                    <el-input-number v-model="form.roleSort" clearable size="small" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio
                                v-for="dict in statusOptions"
                                :key="dict.dictValue"
                                :label="dict.dictValue"
                                :value="dict.dictValue"
                        >{{ dict.dictLabel }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入字典备注" clearable size="small" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
        </el-dialog>
        <!-- 添加修改弹出层结束 -->


        <!-- 查询条件开始 -->
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input
                        v-model="queryParams.roleName"
                        placeholder="请输入角色名称"
                        clearable
                        size="small"
                        style="width:140px"
                />
            </el-form-item>
            <el-form-item label="权限字符" prop="roleCode">
                <el-input
                        v-model="queryParams.roleCode"
                        placeholder="请输入权限字符"
                        clearable
                        size="small"
                        style="width:140px"
                />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                        v-model="queryParams.status"
                        placeholder="可用状态"
                        clearable
                        size="small"
                        style="width:140px"
                >
                    <el-option
                            v-for="dict in statusOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                        v-model="queryParams.dateRange"
                        size="small"
                        style="width:210px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholde="开始日期"
                        end-placeholde="结束日期"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" circle @click="queryTable"></el-button>
                <el-button type="warning" icon="el-icon-refresh" circle @click="refreshQuery"></el-button>
            </el-form-item>
        </el-form>
        <!-- 查询条件结束 -->

        <!-- 表格工具按钮开始 -->
        <el-row :gutter="10" style="margin-bottom: 8px;">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="addRole">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" :disabled="multiple" size="mini" @click="mulDelRole">批量删除</el-button>
            </el-col>

        </el-row>
        <!-- 表格工具按钮结束 -->

        <!-- 数据表格开始 -->
        <el-table  border :data="roleTableList" :ref="multipleTableRole" @selection-change="handleSelectionChangeRole">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="角色ID" align="center" prop="roleId" sortable width="100"/>
            <el-table-column label="角色名称" align="center" prop="roleName" />
            <el-table-column label="权限编码" align="center" prop="roleCode" />
            <el-table-column label="显示顺序" align="center" prop="roleSort" sortable/>
            <el-table-column label="状态" prop="status" align="center" :formatter="statusFormat" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="创建时间" align="center" prop="createTime" sortable width="170" />
            <el-table-column label="操作" align="center" width="280">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.roleId!=1" type="text" icon="el-icon-edit" size="mini" @click="updRole(scope.row)">修改</el-button>
                    <el-button v-if="scope.row.roleId!=1" type="text" icon="el-icon-delete" size="mini" @click="delRole(scope.row)">删除</el-button>
                    <el-button v-if="scope.row.roleId!=1" type="text" icon="el-icon-thumb" size="mini" @click="assignMenu(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 数据表格结束 -->

        <!-- 分页控件开始 -->
        <el-pagination
                v-show="page.total>0"
                :current-page="page.current"
                :page-sizes="[5, 10, 20, 30]"
                :page-size="page.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
        <!-- 分页控件结束 -->

        <!-- 分配权限和菜单弹出层开始 -->
        <el-dialog
                :visible.sync="selectMenuOpen"
                width="400px"
                center
                append-to-body
        >
            <el-tree
                    ref="menu"
                    :data="menuOptions"
                    show-checkbox
                    node-key="menuId"
                    highlight-current
                    empty-text="加载中，请稍后"
                    :props="{id:'menuId',children:'children',label:'menuName'}"
            />
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelectMenuSubmit">确 定</el-button>
        <el-button @click="closeTree">取 消</el-button>
      </span>
        </el-dialog>
        <!-- 分配权限和菜单弹出层结束 -->

    </div>
</template>

<script>
    export default {
        name: "User",
        data() {
            return {
                //表单弹出、隐藏的控值
                formDialogVisible:false,
                //表单标题
                title:'',
                //添加、修改表单对象
                form:{
                    roleSort: 0,
                    status: '0'
                },
                // 非多个禁用
                multiple: true,
                //模糊查询对象容器
                queryParams: {},
                //表格中被选择的所有数据
                multipleTableRole:[],
                //表格数据
                roleTableList:[],
                //状态字典数据
                statusOptions:[],
                //树形控件的所有数据
                menuOptions:[],
                //被选中的树形菜单数据
                checkIds:[],
                //控制树形控件弹出层的开关
                selectMenuOpen:false,
                //当前角色的id
                roleId:0,
                page:{
                  total:0,
                  size:5,
                  current:1
                },
                //表单验证规则
                rules: {
                    roleName: [
                        { required: true, message: '角色名称不能为空', trigger: 'blur' }
                    ],
                    roleCode: [
                        { required: true, message: '权限编码不能为空', trigger: 'blur' }
                    ]
                },
            }
        },
        created() {
            this.initStatus();
            this.initRoleTable();
        },
        methods: {
            /* 表格外按钮触发 */
            queryTable(){  //模糊查询按钮触发
                this.page.current = 1;
                this.initRoleTable();
            },
            refreshQuery(){  //重置模糊查询按钮触发
                this.queryParams={};
                this.initRoleTable();
            },
            addRole(){  //添加按钮触发
                //清除上次表单提交后的提示
                if (this.$refs.form != undefined) {
                    this.$refs.form.clearValidate();
                }
                this.form={
                    roleSort: 0,
                    status: '0'
                }
                //打开对话框
                this.formDialogVisible=true;
                this.title='添加角色';
            },
            handleSelectionChangeRole(val){  //将所有的表格选中数据存放到容器中
                this.multipleTableRole = val;
                //没有行被选中的时候，将批量删除按钮禁用
                this.multiple = !val.length
            },
            mulDelRole(){  //批量删除角色
                this.$confirm('此操作将永久删除以下被选中角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let roleIds = [];
                    for (let i=0;i<this.multipleTableRole.length;i++){
                        roleIds.push(this.multipleTableRole[i].roleId)
                    }
                    this.$http.post("/system/api/role/mulDelRole/"+roleIds).then(result=>{
                        if (result.data.data.length>0){
                            this.$message.error("还有用户使用id为"+result.data.data+"的角色，该角色还不能被删除！");
                        }else {
                            this.$message.success(result.data.msg);
                        }
                        this.initRoleTable();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            /*表格内点击事件触发*/
            updRole(row){  //修改角色信息
                if (this.$refs.form != undefined) {
                    this.$refs.form.clearValidate();
                }
                this.title='修改角色信息';
                //显示弹出对话框
                this.formDialogVisible = true;
                //将当前行的用户id传入表单
                this.form.roleId = row.roleId;
                //采取深克隆的形式
                this.form = JSON.parse(JSON.stringify(row));
            },
            delRole(row){  //删除角色信息
                this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete("/system/api/role/delRole/"+row.roleId).then(result=>{
                        if (result.data.data!=null){
                            this.$message.error("还有用户使用id为"+result.data.data+"的角色，该角色还不能进行删除！");
                        }else {
                            this.$message({
                                showClose: true,
                                message: result.data.msg,
                                type: 'success'
                            });
                        }
                        this.page.current=1;
                        this.initRoleTable();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            /*表单事件*/
            handleSubmit(){  //表单确定提交按钮触发
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.$http.post("/system/api/role/saveOrUpdateRole",this.form).then(result=>{
                            if (result.data.data){
                                this.$message({
                                    showClose: true,
                                    message: result.data.msg,
                                    type: 'success'
                                });
                            }else {
                                this.$message({
                                    showClose: true,
                                    message: '操作失败',
                                    type: 'error'
                                });
                            }
                            //关闭对话框
                            this.formDialogVisible = false;
                            //刷新表单
                            this.form = {};
                            //重置标题
                            this.title='';
                            //刷新表格
                            this.initRoleTable();
                        })
                    }
                })
            },
            cancel(){  //表单取消按钮触发
                this.formDialogVisible=false;
                this.title = '';
            },

            /* 分配菜单的事件 */
            assignMenu(row){  //分配菜单的树形控件
                this.roleId = row.roleId;
                //1、显示树形菜单的弹出层
                this.selectMenuOpen=true;
                //2、获取所有的树形菜单
                this.$http.get("/system/api/menu/list").then(result=>{
                    console.log(result.data.data)
                    this.menuOptions = result.data.data;
                })
                //当前角色所拥有的菜单id
                this.$http.get("/system/api/menu/findByRoleId/"+this.roleId).then(result=>{
                    this.checkIds = result.data.data;
                    //默认选中的树的数据,子菜单未全部选中时，父菜单会是半选状态
                    setTimeout(() =>{
                        result.data.data.forEach(value => {
                            this.$refs.menu.setChecked(value, true, false);
                        })}, 100)
                })
            },
            handleSelectMenuSubmit(){  //获取所有被选中的树状菜单id
                let checkAllIds=this.$refs.menu.getCheckedKeys()
                let checkHalfIds=this.$refs.menu.getHalfCheckedKeys()
                //将两个数组拼接为一个数组
                let keys=checkAllIds.concat(checkHalfIds);
                this.$http.post("/system/api/menu/confirmMenu?roleId="+this.roleId+"&menuIds="+keys).then(result=>{
                    this.selectMenuOpen=false;
                    this.$message.success("分配权限成功")
                })
            },
            closeTree(){  //关闭菜单的树形控件
                //关闭树形菜单的弹出层
                this.selectMenuOpen=false;
            },

            /*  初始化数据  */
            initStatus(){ //初始化状态字典
                this.$http.get("/system/api/dict/data/findByType/sys_normal_disable").then(result=>{
                    this.statusOptions = result.data.data;
                })
            },
            statusFormat(row){  //状态字典解析
                let v = row.status;
                return this.formatDict2(this.statusOptions,v)
            },
            initRoleTable(){  //初始化角色数据表格
                this.$http.post("/system/api/role/list/"+this.page.current+"/"+this.page.size,this.queryParams).then(result=>{
                    this.roleTableList = result.data.data.records;
                    this.page.total = result.data.data.total;
                })
            },

            // 分页pageSize变化时触发
            handleSizeChange(val) {
                this.page.size = val
                // 重新查询
                this.initRoleTable()
            },
            // 点击上一页  下一页，跳转到哪一页面时触发
            handleCurrentChange(val) {
                this.page.current = val
                // 重新查询
                this.initRoleTable()
            },
        }
    }
</script>

<style scoped>

</style>
